package org.pjug.linuxadvices.listeners;

import org.pjug.linuxadvices.database.DBConnection;
import javax.servlet.*;

import org.apache.log4j.Logger;

public class ContextDatabaseListener implements ServletContextListener {
	Logger logger = Logger.getLogger(ContextDatabaseListener.class); 
	
	private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        try {
            DBConnection dbConnection = new DBConnection();
            context.setAttribute("dbConnection", dbConnection);
        } catch (Exception ex) {
            logger.warn("Can not create new dbConnection " + ex.getMessage());
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
        context = event.getServletContext();
        DBConnection dbConnection = (DBConnection)context.getAttribute("dbConnection");
        dbConnection.close();
        context.removeAttribute("dbConnection");
    }
}
